package com.example.aspect;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class RetrofitLogAspect {

  @Pointcut(value=
     " execution(public * com.example.controller.*.*(..)) "
//             + "|| execution(public * com.qdingnet.qdp2.taurus.client.*Client.*(..)) "+
//    "|| execution(public * com.qd2.platform.message.retrofit.client.*Client.*(..)) "+
//    "|| execution(public * com.qdingnet.qdp2.housekeeper.client.*Client.*(..)) "

  )//两个..代表所有子目录，最后括号里的两个..代表所有参数
  public void logPointCut() {
  }

  @Before("logPointCut()")
  public void doBefore(JoinPoint joinPoint){
    try {
      Object[] objects = joinPoint.getArgs();
      if (objects!=null) {
        for (Object object:objects) {
          if (object instanceof String) {
            continue;
          }
          log.info("{}.{},req:{}",joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName(), JSONUtil.toJsonStr(object));
        }
      }

    }catch (Exception e) {
      log.error("doBefore error",e);
    }
  }

  @AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的参数名一致
  public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {
    try {
      log.info("{}.{},resp:{}",joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName(), JSONUtil.toJsonStr(ret));
    } catch (Exception e){
      log.error("doAfterReturning error",e);
    }
  }

  @Around("logPointCut()")
  public Object doAround(ProceedingJoinPoint pjp){
    Object ob = null;// ob 为方法的返回值
    try {
        ob = pjp.proceed();
    } catch (Throwable e) {
        log.error("doAround error",e);
    }
    return ob;
  }

}
